<?php
/*  current unix timestamp  */
define('NOW', isset($_SERVER['REQUEST_TIME']) ? (int) $_SERVER['REQUEST_TIME'] : time());
define('TIME', NOW);

/**
 * A quick function to get a Table Object
 *
 * @param string|array $table
 * @param string $guid
 * @return Table
 */
function T($table, $guid = null)
{
    return Table::getInstance($table, $guid);
}

require_once DONE_PATH . 'Object.php';
class Done extends Object
{
	public $controller, $action, $args, $class;
    private static $__classes = array();

	public function __construct()
	{
		
	}
	
	public static function init()
	{
        // 注册AUTOLOAD方法
        set_include_path(get_include_path() . PATH_SEPARATOR. DONE_PATH . PATH_SEPARATOR . MODEL_PATH);
        spl_autoload_register(array('Done', 'autoLoad'));
        // 设定错误和异常处理
        set_error_handler(array('Done','errorHandler'));
        set_exception_handler(array('Done','exceptionHandler'));
	}
	
	private static function autoLoad($class_name)
	{
		if(class_exists($class_name)) {
			return;
		}
		if(!isset(self::$__classes[$class_name])) {
			self::$__classes[$class_name] =  @require_once str_replace('_', '/', $class_name) . '.php';
		} else {
			return self::$__classes[$class_name];
		}
	}
	
	public function setController($controller)
	{
		if (!preg_match("/^[0-9a-z_]+$/i", $controller)) {
			$controller = strip_tags($controller);
			if(DEBUG_MODE) {
				throw new Exception('Illegal controller name');
			} else {
				self::showMessage('404');
			}
		}
		
		$file = CONTROLLER_PATH . $controller . '.php';
		
		if(!file_exists($file)) {
			if (DEBUG_MODE) {
				throw new Exception('Controller file does not exist');
			} else {
				self::showMessage('404');
			}
		}
		require_once($file);
		
		$this->class = ucfirst($controller);
		$this->controller = $this->class;
	}
	
	public function setAction($action)
	{
		if (!preg_match("/^[0-9a-z_]+$/i", $action)) {
			$action = strip_tags($action);
			self::showMessage(DEBUG_MODE ? "Illegal action name" : '404');
		}
		
		$this->action = $action;
	}
	
	public function setArgs($args)
	{
		$this->args = $args;
	}
	
	public function execute($controller = null, $action = null, $args = array())
	{
		$router = Factory::router();
		$router->execute();
		if(empty($controller)) {
			$controller = $router->controller;
		}
		if(empty($action)) {
			$action = $router->action;
		}
		if (empty($args)) {
			$args = $router->args;
		}

		
		$this->setController($controller);
		$this->setAction($action);
		$this->setArgs($args);
		$obj = new $this->class($this);
	
		$response = $obj->dispatch();
		
		
	}
	
	public static function showMessage($message, $url = null, $ms = 2000, $success = false)
	{
		$template =  Factory::template();
		$template->assign('message', $message);
		$template->assign('url', $url);
		$template->assign('ms', $ms);
		$template->assign('success', $success);
		$template->display('system/showmessage.html');
		exit;
	}
	
	public static function exceptionHandler($e) 
	{
       $e = nl2br($e);
       die($e);
    }
    
	public static function errorHandler($errno, $errstr, $errfile, $errline)
	{
		$errorStr = "[$errno] $errstr ".basename($errfile)." 第 $errline 行.";
		$errorStr = nl2br($errorStr);
		die($errorStr);
	}
}

Done::init();

function pages_url($url, $page, $mode = false)
{
	//if (!$url) $url = URL;
	if (strpos($url, '$page') === false)
	{
		$url = url_query($url, array('page'=>$page), $mode);
	}
	else 
	{
		eval("\$url = \"$url\";");
	}
	return $url;
}
function url_query($url, $query = array(), $mode = false)
{
	if ($query)
	{
		$data = parse_url($url);
		if (!$data) return false;
		if (isset($data['query']))
		{
			parse_str($data['query'], $q);
			$query = array_merge($q, $query);
		}
		$data['query'] = http_build_query($query);
		$url = http_build_url($data, $mode);
	}
	return $url;
}

function http_build_url($data, $mode = false)
{
	if (!is_array($data)) return false;
	$url = isset($data['scheme']) ? $data['scheme'].'://' : '';
	if (isset($data['user'])) $url .= $data['user'];
	if (isset($data['pass'])) $url .= ':'.$data['pass'];
	if (isset($data['user'])) $url .= '@';
	if (isset($data['host'])) $url .= $data['host'];
	if (isset($data['port'])) $url .= ':'.$data['port'];
	if (isset($data['path'])) $url .= $data['path'];
	if (isset($data['query'])) $url .= '?'.($mode ? str_replace('&', '&amp;', $data['query']) : $data['query']);
	if (isset($data['fragment'])) $url .= '#'.$data['fragment'];
	return $url;
}